from django.core.exceptions import ImproperlyConfigured
from django.contrib.admin.sites import NotRegistered


REQUIRED_KEYS = ['models', ]

def clean_layout(layout, registry):
    _check_istuple(layout, "layout")
    if not len(layout):
        raise ImproperlyConfigured("`layout` contains no sections" % nr)
        
    all_models = []
    for j,section in enumerate(layout):
        nr = j+1
        _check_istuple(layout, "section #%d" % nr)
        if len(section) != 2:
            raise ImproperlyConfigured("Section #%d: Expected tuple or list "
                    "of length 2")
        section_name, section_dict = section

        _check_isdict(section_dict, "Section #%d" % nr)

        for key in REQUIRED_KEYS:
            if key not in section_dict.keys():
                raise ImproperlyConfigured("Section #%d: `%s` key is required."
                        % (nr, key))
        
        _check_istuple(section_dict['models'], "Models in section #%d" % nr)

        if len(section_dict['models']) < 2:
            raise ImproperlyConfigured("Section #%d contains no models" % nr)
        
        model_list = []
        prefix = section_dict['models'][0]
        for model_name in section_dict['models'][1:]:
            if prefix:
                import_path = "%s.%s" % (section_dict['models'][0], model_name)
            else:
                import_path = model_name
            try: 
                dot = import_path.rindex('.') 
            except ValueError: 
                raise ImproperlyConfigured("`%s` is not a model class."
                            % import_path) 
            module, classname = import_path[:dot], import_path[dot+1:]
            try:
                mod = __import__(module, {}, {}, [''])
            except ImportError, e:
                raise ImproperlyConfigured('Error importing module `%s`: %s"'
                        % (module, e))
            try:
                model = getattr(mod, classname)
            except AttributeError:
                raise ImproperlyConfigured("The module `%s` does not define "
                        " a `%s` class." % (module, classname))
            try:
                registry[model]
            except KeyError:
                raise NotRegistered('The model %s is not registered'
                        % model.__name__)
            if model in all_models:
                raise ImproperlyConfigured("Section #%d: the model `%s` is "
                        "already in layout." % (nr, import_path))

            all_models.append(model)
            model_list.append(model)
        section_dict['models'] = model_list
    return list(layout)

def _check_istuple(obj, label):
    if not isinstance(obj, (list, tuple)):
        raise ImproperlyConfigured("`%s` must be a "
            "list or tuple." % label)

def _check_isdict(obj, label):
    if not isinstance(obj, dict):
        raise ImproperlyConfigured("`%s` must be a dictionary." % label)
